package com.zenithmind.gateway.auth;

import com.zenithmind.common.constant.CommonConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

/**
 * 默认请求头设置器实现
 * 专门负责设置HTTP请求头信息
 * 遵循单一职责原则：只负责请求头的设置逻辑
 */
@Slf4j
@Component
public class DefaultRequestHeaderSetter implements RequestHeaderSetter {

    // 用户信息相关常量
    private static final String USER_ID_HEADER = "X-User-ID";
    private static final String USER_ROLES_HEADER = "X-User-Roles";
    private static final String AUTH_HEADER = "Authorization";
    
    // 网关验证头，表示请求已通过网关验证
    private static final String GATEWAY_VERIFIED_HEADER = "X-Gateway-Verified";
    // 内部令牌，微服务之间信任的标识
    private static final String INTERNAL_TOKEN_VALUE = "trusted-internal-request";

    @Override
    public void setUserInfoHeaders(ServerHttpRequest.Builder requestBuilder, UserInfoParser.UserInfo userInfo) {
        log.trace("设置用户信息头");
        
        // 将用户信息传递到下游服务
        if (StringUtils.isNotBlank(userInfo.getUserId())) {
            requestBuilder.header(CommonConstants.USER_ID_HEADER, userInfo.getUserId());
            requestBuilder.header(USER_ID_HEADER, userInfo.getUserId());
            log.trace("设置用户ID头: {}", userInfo.getUserId());
        }
        
        if (StringUtils.isNotBlank(userInfo.getUserRoles())) {
            requestBuilder.header(CommonConstants.USER_ROLES_HEADER, userInfo.getUserRoles());
            requestBuilder.header(USER_ROLES_HEADER, userInfo.getUserRoles());
            log.trace("设置用户角色头: {}", userInfo.getUserRoles());
        }
    }

    @Override
    public void setGatewayVerificationHeaders(ServerHttpRequest.Builder requestBuilder) {
        log.trace("设置网关验证头");
        
        // 添加网关验证头，表示该请求来自网关
        requestBuilder.header(GATEWAY_VERIFIED_HEADER, INTERNAL_TOKEN_VALUE);
    }

    @Override
    public void setGuestInfoHeaders(ServerHttpRequest.Builder requestBuilder) {
        log.trace("设置访客信息头");
        
        requestBuilder.header(AUTH_HEADER, "Bearer guest-token-for-public-endpoints");
        requestBuilder.header(USER_ID_HEADER, "guest");
        requestBuilder.header(USER_ROLES_HEADER, "ROLE_GUEST");
    }
}
